from django import template
from apps.help.models import FAQ
from apps.course.functions import course_reverse
register = template.Library()

class HelpList:
    def __init__(self, qs):
        self.list = sorted(list(qs), key = lambda faq: "%s %s" % (faq.for_admin, faq.question_id))
    
    def __iter__(self):
        return self.list.__iter__()
    
class BaseHelpNode(template.Node):
    def handle_token(cls, parser, token):
        tokens = token.contents.split()
        if tokens[1] != 'for':
            raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
        if tokens[-2] != 'as':
            raise template.TemplateSyntaxError("Second-to-last argument in %r tag must be 'as'" % tokens[0])
        if len(tokens) != 5:
            raise template.TemplateSyntaxError("%r must have 4 arguments: 'get_help_list for category[.subcategory.sub-subcategory...] as varname'" % tokens[0])
        category = tokens[2]
        varname = tokens[4]
        return cls(category,varname)
    handle_token = classmethod(handle_token)
    
    def __init__(self, category, varname):
        self.category = category
        self.as_varname = varname
        self.admin = False
        self.qs = None
    def get_query_set(self, context):
        TheCourse = context['course']
        self.qs = FAQ.find(course=TheCourse.course_id, category=self.category, include_admin=self.admin)
        return self.qs
    def render(self, context):
        try: self.category = template.Variable(self.category).resolve(context)
        except: self.category = self.category.lower()
        qs = self.process_queryset(context,self.get_query_set(context))
        context[self.as_varname] = self.get_context_value_from_queryset(context, qs)
        return ''
    def process_queryset(self, context,qs):
        if qs:
            for faq in qs:
                faq.url = course_reverse('apps.help.views.FAQ_popup',context['course'],args=[faq.question_link])
        return qs
    def get_context_value_from_queryset(self, context, qs):
        """Subclasses should override this."""
        raise NotImplementedError
    
class HelpListNode(BaseHelpNode):
    def get_context_value_from_queryset(self,context, qs):
        return HelpList(qs) if qs else None

class AdminHelpListNode(HelpListNode):
    def __init__(self, category, varname):
        super(AdminHelpListNode, self).__init__(category, varname)
        self.admin = True
    
def get_help_list(parser, token):
    """
    {% get_help_list for category as varname %}
    {% get_help_list for category.subcategory as varname %}
    {% get_help_list for category.subcategory.sub-subcategory as varname %}
    
    Returns only help objects that are non-admin
    """
    return HelpListNode.handle_token(parser, token)
register.tag(get_help_list)

def get_admin_help_list(parser, token):
    """
    {% get_help_list for category as varname %}
    {% get_help_list for category.subcategory as varname %}
    {% get_help_list for category.subcategory.sub-subcategory as varname %}
    
    Returns all applicable help objects (admin and non-admin)
    """
    return AdminHelpListNode.handle_token(parser, token)
register.tag(get_admin_help_list)
